package com.cn.gmall.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.cn.gmall.common.mqconst.MqConst;
import com.cn.gmall.common.service.RabbitService;
import com.cn.gmall.model.enums.PaymentStatus;
import com.cn.gmall.model.enums.PaymentType;
import com.cn.gmall.model.order.OrderInfo;
import com.cn.gmall.model.payment.PaymentInfo;
import com.cn.gmall.payment.mapper.PaymentInfoMapper;
import com.cn.gmall.payment.service.PaymentInfoService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import javax.annotation.Resource;

import java.util.Date;
import java.util.Map;

@Service
public class PaymentInfoServiceImpl implements PaymentInfoService {

    @Autowired
    PaymentInfoMapper paymentInfoMapper;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private RabbitService rabbitService;


    /***
     * 支付记录查询 /
     * @param out_trade_no  对外业务编号
     * @param paymentType 支付方式
     * @return
     */
    @Override
    public PaymentInfo getPaymentInfo(String out_trade_no, String paymentType) {

      /*  return paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOutTradeNo, out_trade_no)
                .eq(PaymentInfo::getPaymentType, name));*/
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOutTradeNo,out_trade_no);
        if (!StringUtils.isEmpty(paymentType)){
            queryWrapper.eq(PaymentInfo::getPaymentType,paymentType);
        }

        return paymentInfoMapper.selectOne(queryWrapper);
    }

    /***
     * 修改订单状态 为 PAID
     * @param out_trade_no
     * @param paymentType
     * @param paramsMap
     * @return
     */
    @Override
    public boolean paySuccess(String out_trade_no, String paymentType, Map<String, String> paramsMap) {
        try {
//        条件修改
            PaymentInfo paymentInfo = new PaymentInfo();

            paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
//        支付
            paymentInfo.setTradeNo(paramsMap.get("trade_no"));
//  设置回调时间
            paymentInfo.setCallbackTime(new Date());
//        设置回调信息

            paymentInfo.setCallbackContent(JSONObject.toJSONString(paramsMap));
/****JSON.toJSONString() 将java对象转成字符串
 * JSONObject.toJSONString() 将json对象转成字符串
 */

/***LambdaQueryWrapper 需要手动创建对象，并通过对象调用方法来构建查询条件
 *LambdaQueryChainWrapper<>() 可以链式查询 和 排序
 * 然后通过该对象进行链式操作，
 * 例如queryChainWrapper.eq("column", value).orderByAsc("column")。
 */
            int update = updateOrderStatus(out_trade_no, paymentType, paymentInfo);
            if (update > 0) {
//    发布更新订单状态的消息
                rabbitService.sendMessage(
                        MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,
                        MqConst.ROUTING_PAYMENT_PAY,
                        out_trade_no
                        );
// ----发送消息 修改库存-------------------

                return true;
            }


        } catch (Exception e) {
            redisTemplate.delete(paramsMap.get("notify_id"));
            e.printStackTrace();
        }
        return false;

    }

    /***
     *修改支付状态
     * @param out_trade_no
     * @param paymentType
     * @param paymentInfo
     * @return
     */
    @Override
    public int updateOrderStatus(String out_trade_no, String paymentType, PaymentInfo paymentInfo) {
        //        修改支付记录
        int update = paymentInfoMapper.update(paymentInfo, new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOutTradeNo, out_trade_no)
                .eq(PaymentInfo::getPaymentType, paymentType));
        return update;
    }


    /**
     * 保存支付记录 在对接支付宝前
     *
     * @param orderInfo
     */
    @Override
    public void savePaymentInfo(OrderInfo orderInfo) {
//        先判断是否存在 不重复提交


//        将orderInfo 信息转换成 PaymentInfo
        PaymentInfo paymentInfo = new PaymentInfo();

        paymentInfo.setCreateTime(new Date());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(PaymentType.ALIPAY.name());
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
        paymentInfo.setSubject(orderInfo.getTradeBody());
        //paymentInfo.setSubject("test");
        paymentInfo.setTotalAmount(orderInfo.getTotalAmount());


//        保存
        paymentInfoMapper.insert(paymentInfo);

    }

}
